package com.cloudweb.oa.controller.mobile;

import cn.js.fan.db.ResultIterator;
import cn.js.fan.db.ResultRecord;
import cn.js.fan.db.SQLFilter;
import cn.js.fan.util.DateUtil;
import cn.js.fan.util.ErrMsgException;
import cn.js.fan.util.ParamUtil;
import cn.js.fan.util.StrUtil;
import com.alibaba.fastjson.JSONObject;
import com.cloudweb.oa.cache.UserCache;
import com.cloudweb.oa.entity.DeptUser;
import com.cloudweb.oa.entity.Role;
import com.cloudweb.oa.entity.User;
import com.cloudweb.oa.security.AuthUtil;
import com.cloudweb.oa.service.HomeService;
import com.cloudweb.oa.service.LeaveBalanceService;
import com.cloudweb.oa.vo.Result;
import com.cloudwebsoft.framework.db.JdbcTemplate;
import com.cloudwebsoft.framework.util.LogUtil;
import com.redmoon.oa.attendance.AttendanceMgr;
import com.redmoon.oa.attendance.ShiftScheduleMgr;
import com.redmoon.oa.flow.FormDb;
import com.redmoon.oa.visual.FormDAO;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.json.JSONException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.sql.SQLException;
import java.time.LocalDate;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

@Controller
public class MobileHrController {

    @Autowired
    HomeService homeService;

    @Autowired
    AuthUtil authUtil;

    @Autowired
    UserCache userCache;

    @Autowired
    HttpServletRequest request;

    @Autowired
    LeaveBalanceService leaveBalanceService;

    @ApiOperation(value = "打卡页面", notes = "打卡页面", httpMethod = "POST")
    @ResponseBody
    @RequestMapping(value = "/m/hr/punchPage")
    public Result<Object> punchPage() throws SQLException {
        JSONObject json = new JSONObject();
        String userName = authUtil.getUserName();

        Date dt = new Date();
        Object[] ary = ShiftScheduleMgr.getShiftDAO(userName, dt);
        FormDAO fdao = (FormDAO) ary[0];
        String location = "", radius = "";
        double lngLoc = 0, latLoc = 0;
        boolean isAbnormal = false;
        boolean hasLocation = false;

        String shiftName = "";
        boolean hasShift = false;
        if (fdao != null) {
            hasShift = true;
            shiftName = fdao.getFieldValue("name");
            location = fdao.getFieldValue("location");
            String[] aryLoc = StrUtil.split(location, ",");
            if (aryLoc != null) {
                hasLocation = true;
                lngLoc = StrUtil.toDouble(aryLoc[0]);
                latLoc = StrUtil.toDouble(aryLoc[1]);
                location = aryLoc[2];
            }
            radius = fdao.getFieldValue("radius");
            isAbnormal = "1".equals(fdao.getFieldValue("is_abnormal"));
        }

        JdbcTemplate jt = new JdbcTemplate();
        String sqlMouthSignIn = "select count(*) from ft_kaoqin_time_sign where " + SQLFilter.year("sign_time") + "= ? and " + SQLFilter.month("sign_time") + "= ? and name = ?";
        String sqlMouthAbnormal = "select count(*) from ft_kaoqin_time_sign t where t.sign_result<>0 and " + SQLFilter.year("sign_time") + "= ? and " + SQLFilter.month("sign_time") + "= ? and name = ?";
        int mouthSignInCount = 0;
        int mouthAbnormalCount = 0;
        Calendar calendar = Calendar.getInstance();
        int nowYear;
//        nowYear = DateUtil.getYear(new Date());
        int nowMouth = calendar.get(Calendar.MONTH) + 1;
        nowYear = calendar.get(Calendar.YEAR);
        //String nowUser = new com.redmoon.oa.pvg.Privilege().getUser(request);
        String nowUser = authUtil.getUserName();

        ResultIterator riSignIn = jt.executeQuery(sqlMouthSignIn, new Object[]{nowYear, nowMouth, nowUser});
        if (riSignIn.hasNext()) {
            ResultRecord rr = riSignIn.next();
            mouthSignInCount += rr.getInt(1);
        }

        ResultIterator riAbnormal = jt.executeQuery(sqlMouthAbnormal, new Object[]{nowYear, nowMouth, nowUser});
        if (riAbnormal.hasNext()) {
            ResultRecord rr = riAbnormal.next();
            mouthAbnormalCount += rr.getInt(1);
        }

        json.put("hasShift", hasShift);
        json.put("shiftName", shiftName);
        json.put("hasLocation", hasLocation);
        json.put("lngLoc", lngLoc);
        json.put("latLoc", latLoc);
        json.put("location", location);
        json.put("isAbnormal", isAbnormal);
        json.put("mouthSignInCount", mouthSignInCount);
        json.put("mouthAbnormalCount", mouthAbnormalCount);

        if ("".equals(radius)) {
            radius = "200";
        }
        json.put("radius", radius);

        int[] aryPunch = new int[2];
        aryPunch[0] = -1;
        aryPunch[1] = AttendanceMgr.NORMAL;
        String typeDesc = "";
        int typeOfDuty = 1;
        boolean isBtnGrey = false;
        if (fdao != null) {
            aryPunch = AttendanceMgr.getPunchType(userName, new java.util.Date());
            typeOfDuty = aryPunch[0];
            if (aryPunch[0] == -1) {
                typeDesc = "非打卡时间";
            } else {
                // 如果已打卡
                if (AttendanceMgr.isPunched(userName, aryPunch[0])) {
                    typeDesc = AttendanceMgr.getPunchTypeDesc(aryPunch[0]) + "已打卡";
                    aryPunch[0] = -1;
                } else {
                    typeDesc = AttendanceMgr.getPunchTypeDesc(aryPunch[0]) + AttendanceMgr.getPunchStatusDesc(aryPunch[1]) + "打卡";
                }
            }
            if (aryPunch[0] == -1) {
                isBtnGrey = true;
            }
            if (!hasLocation) {
                aryPunch[0] = -1;
                typeDesc = "未设置打卡地点";
            }
        } else {
            typeDesc = "无需打卡";
        }

        json.put("typeDesc", typeDesc);
        json.put("type", typeOfDuty);
        json.put("typeStatus", aryPunch[1]);
        json.put("isBtnGrey", isBtnGrey);

        return new Result<>(json);
    }

    @RequestMapping(value = "/m/hr/punchResult")
    public String punchResult(Model model) {
        model.addAttribute("nav", homeService.getNav());
        int result = ParamUtil.getInt(request, "result", -1);
        int min = ParamUtil.getInt(request, "min", 0);
        // String address = ParamUtil.get(request, "address");
        String address = request.getParameter("address");
        boolean isLocationAbnormal = ParamUtil.getBoolean(request, "isLocationAbnormal", false);

        long id = ParamUtil.getLong(request, "id", -1);

        address = StrUtil.UnicodeToUTF8(address);
        Date dt = new Date();
        String dtStr = DateUtil.format(dt, "HH:mm");
        model.addAttribute("address", address);
        model.addAttribute("dtStr", dtStr);
        model.addAttribute("id", id);
        model.addAttribute("isLocationAbnormal", isLocationAbnormal);
        model.addAttribute("result", result);
        model.addAttribute("min", min);
        model.addAttribute("userName", authUtil.getUserName());

        return "th/m/hr/punch";
    }

    @ApiOperation(value = "打卡", notes = "打卡", httpMethod = "POST")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "lng", value = "经度", required = true, dataType = "Double"),
            @ApiImplicitParam(name = "lat", value = "纬度", required = true, dataType = "Double"),
            @ApiImplicitParam(name = "address", value = "地址", required = true, dataType = "String"),
            @ApiImplicitParam(name = "type", value = "类型", required = true, dataType = "Integer"),
    })
    @ResponseBody
    @RequestMapping(value = "/m/hr/punch", method = RequestMethod.POST, produces = {"text/html;charset=UTF-8;", "application/json;"})
    public Result<Object> punch(@RequestParam Double lng, @RequestParam Double lat, @RequestParam(required = false) String address, @RequestParam Integer type) {
        long[] r = new long[3];
        try {
            r = AttendanceMgr.punch(authUtil.getUserName(), lat, lng, address, type);
        } catch (ErrMsgException e) {
            return new Result<>(false, e.getMessage());
        }

        if (r[0] != -1) {
            com.alibaba.fastjson.JSONObject json = new com.alibaba.fastjson.JSONObject();
            json.put("result", r[0]);
            json.put("min", r[1]);
            json.put("id", r[2]); // 打卡記錄的ID
            return new Result<>(json);
        } else {
            return new Result<>(false);
        }
    }

    @ApiOperation(value = "报告原因", notes = "报告原因", httpMethod = "POST")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "ID", required = true, dataType = "Long"),
            @ApiImplicitParam(name = "remark", value = "原因", required = true, dataType = "String"),
    })
    @ResponseBody
    @RequestMapping(value = "/m/hr/punchRemark", method = RequestMethod.POST, produces = {"text/html;charset=UTF-8;", "application/json;"})
    public Result<Object> punchRemark(@RequestParam Long id, @RequestParam String remark) {
        try {
            FormDb fd = new FormDb();
            fd = fd.getFormDb("kaoqin_time_sign");
            FormDAO fdao = new FormDAO();
            fdao = fdao.getFormDAOByCache(id, fd);
            fdao.setFieldValue("remark", remark);
            fdao.save();
        } catch (ErrMsgException e) {
            return new Result<>(false, e.getMessage());
        }
        return new Result<>();
    }
}
